{extend name="public/base"/}
{block name="style"}
<style>
    .layui-table th{text-align:center;}
    .layui-table td{text-align:center;}
</style>
{/block}
{block name="content"}
<form class="layui-form" action="{:url('pur/purchase/add')}" method="post" lay-filter="purchase-form" id="purchase-form">
    {:token()}
    {if isset($purchase)}
    <input type="hidden" name="purchase.purchase_id" value="{$purchase.purchase_id}">
    {/if}
    <div class="layui-form-item">
        <div class="layui-col-xs3">
            <label class="layui-form-label">单号</label>
            <div class="layui-input-block">
                <input type="text" value="{$purchase?$purchase.purchase_sn:''}" readonly placeholder="保存后自动生成" name="purchase.purchase_sn" class="layui-input">
            </div>
        </div>
        <div class="layui-col-xs3">
            <label class="layui-form-label xrequired">供应商</label>
            <div class="layui-input-block">
                <select name="purchase.producer_id" lay-search lay-reqText="供应商必选" lay-verify="required" lay-filter="producer">
                    <option value="">请选择</option>
                    {foreach $producer as $p}
                    <option value="{$p.producer_id}" {if isset($purchase) && $purchase.producer_id==$p.producer_id}selected{/if}>{$p.name}</option>
                    {/foreach}
                </select>
            </div>
        </div>
        <div class="layui-col-xs3">
            <label class="layui-form-label xrequired">付款方式</label>
            <div class="layui-input-block">
                <select name="purchase.pay_type" lay-verify="required" lay-filter="pay-type" id="purchase-pay-type">
                    <option value="">请选择</option>
                    {foreach $pay_type as $k => $t}
                    <option value="{$k}" {if isset($purchase) && $purchase->pay_type==$t}selected{/if}>{$t}</option>
                    {/foreach}
                </select>
            </div>
        </div>
        <div class="layui-col-xs3">
            <label class="layui-form-label">是否开发票</label>
            <div class="layui-input-block">
                <select name="purchase.is_invoice" lay-filter="invoice" id="purchase-invoice">
                    {foreach $is_invoice as $k=>$v}
                    <option value="{$k}" {if isset($purchase) && $purchase.is_invoice==$k}selected{/if}>{$v}</option>
                    {/foreach}
                </select>
            </div>
        </div>
    </div>
    <div class="layui-form-item">
        <div class="layui-col-xs3">
            <label class="layui-form-label">账期（天）</label>
            <div class="layui-input-block">
                <input type="number" placeholder="天" id="purchase-credit-day" lay-verify="egtZero" value="{$purchase?$purchase.credit_day:''}" name="purchase.credit_day" class="layui-input">
            </div>
        </div>
        <div class="layui-col-xs3">
            <label class="layui-form-label xrequired">交货日期</label>
            <div class="layui-input-block">
                <input type="text" value="{$purchase?$purchase.delivery_date:''}" autocomplete="off" lay-reqText="交货日期必填" lay-verify="required" name="purchase.delivery_date" class="laydate-date-future layui-input">
            </div>
        </div>
        <div class="layui-col-xs3">
            <label class="layui-form-label">预计到货</label>
            <div class="layui-input-block">
                <input type="text" id="estimate-date" value="{$purchase?$purchase.estimate_date:''}" name="purchase.estimate_date" autocomplete="off" class="laydate-date-future layui-input">
            </div>
        </div>
        <div class="layui-col-xs3">
            <label class="layui-form-label">物流费用</label>
            <div class="layui-input-block">
                <input type="number" value="{$purchase?$purchase.logistics_price|abs:0}" name="purchase.logistics_price" autocomplete="off" class="layui-input">
            </div>
        </div>
    </div>
    <div class="layui-form-item">
        <div class="layui-col-xs3">
            <label class="layui-form-label">供应商优惠</label>
            <div class="layui-input-block">
                <input type="number" value="{$purchase?$purchase.pro_money|abs:0}" name="purchase.pro_money" autocomplete="off" class="layui-input">
            </div>
        </div>
        <div class="layui-col-xs3">
            <label class="layui-form-label xrequired">调入仓库</label>
            <div class="layui-input-block">
                <select name="purchase.warehouse_id" lay-search lay-filter="warehouse" lay-verify="required" lay-reqText="仓库必选">
                    <option value="">请选择</option>
                    {foreach $warehouse as $w}
                    <option value="{$w.warehouse_id}" {if isset($purchase) && $purchase.warehouse_id==$w.warehouse_id}selected{/if}>{$w.name}</option>
                    {/foreach}
                </select>
            </div>
        </div>
        <div class="layui-col-xs3">
            <label class="layui-form-label xrequired">联系人</label>
            <div class="layui-input-block">
                <input type="text" value="{$purchase?$purchase.contacts:''}" id="contacts" lay-reqText="联系人必填" lay-verify="required" name="purchase.contacts" autocomplete="off" class="layui-input">
            </div>
        </div>
        <div class="layui-col-xs3">
            <label class="layui-form-label xrequired">电话</label>
            <div class="layui-input-block">
                <input type="text" value="{$purchase?$purchase.phone:''}" id="phone" lay-reqText="电话必填" lay-verify="required" name="purchase.phone" class="layui-input">
            </div>
        </div>
    </div>
    <div class="layui-form-item">
        <div class="layui-col-xs6">
            <label class="layui-form-label xrequired">收货地址</label>
            <div class="layui-input-block">
                <input type="text" value="{$purchase?$purchase.address:''}" id="address" lay-reqText="收货地址必填" lay-verify="required" name="purchase.address" class="layui-input">
            </div>
        </div>
        <div class="layui-col-xs3">
            <label class="layui-form-label">备注</label>
            <div class="layui-input-block">
                <input type="text" value="{$purchase?$purchase.remark:''}" name="purchase.remark" autocomplete="off" class="layui-input">
            </div>
        </div>
        <div class="layui-col-xs6"><div id="more-select-sku"></div></div>
    </div>
    <div class="layui-form-item job-flow-margin">
        {include file="public/attachment" /}
    </div>
    <div class="layui-form-item job-flow-margin">
        {include file="public/jobFlow" /}
    </div>
    <div class="layui-form-item">
        <div class="layui-col-xs6">
            <div class="layui-input-block" style="margin-left: 0px;">
                <div id="product-sku" msg="批量输入SKU"></div>
            </div>
        </div>
        <div class="layui-col-xs6">
            <div class="layui-btn-group" style="margin-right: 30px; float: right;">
                {if !empty($purchase) && \app\common\model\JobFlowModule::isCheckIng($purchase)}
                <button type="button" item="{$purchase.purchase_id}" class="layui-btn check-job-flow-reload">审批</button>
                <button type="button" item="{$purchase.purchase_id}" id="purchase-cancel" class="layui-btn">取消</button>
                {/if}
                {if !empty($purchase) && \app\common\model\JobFlowModule::isCheckFinish($purchase) && in_array($purchase->getData('order_status'), $order_status_wait)}
                <button type="button" item="{$purchase.purchase_id}" id="purchase-business" class="layui-btn">下单</button>
                {/if}
                {if !empty($purchase) && $purchase->getData('order_status') == $purchase_ing && $purchase->getData('pay_status') == $pay_status_none}
                <button type="button" item="{$purchase.purchase_id}" id="purchase-payment" class="layui-btn">申请付款</button>
                {/if}
                <button type="button" item="{$attachment_type_contract}" id="upload-contract" class="layui-btn">上传合同</button>
                <input type="hidden" id="attachment-contract" name="attachment.contract"/>
                <input type="hidden"  id="attachment-invoice" name="attachment.invoice"/>
                <button type="button" item="{$attachment_type_invoice}" id="upload-invoice" class="layui-btn">上传发票</button>
            </div>
        </div>
        <table class="layui-table" style="margin-top: 0px;">
            <thead>
                <tr>
                    <th width="100">图片</th>
                    <th width="230">SKU</th>
                    <th width="100">数量</th>
                    <th width="100">单价</th>
                    <th>总价</th>
                    <th>采购链接</th>
                    <th>备注</th>
                    <th>操作</th>
                </tr>
            </thead>
            <tbody>
            {if isset($purchase)}
            {foreach $purchase->info as $info}
            <tr class="data-sku-row">
                <td><img class="sku-img" src="{$info.image_url}"/></td>
                <td>
                    <div class="more-select-sku" item="{$info.sku}"></div>
                    <!--<input type="text" value="{$info.sku}" class="layui-input sku" lay-reqText="sku必填" lay-verify="required" name="info.sku[]">-->
                </td>
                <td><input class="layui-input qty" value="{$info.qty}" type="number" name="info.qty[]" lay-reqText="数量必填" lay-verify="required"/></td>
                <td><input class="layui-input price" value="{$info.price|abs}" type="number" lay-reqText="单价必填" lay-verify="required" name="info.price[]"/></td>
                <td class="sum-one-price">{$info.qty * $info.price|abs}</td>
                <td>
                    <div class="layui-input-inline" style="margin-right: 0px; width: 80%;">
                        <input class="layui-input purl" value="{$info.url}" type="text" name="info.url[]" lay-verify="emptyUrl"/>
                    </div>
                    <button type="button" class="layui-btn layui-btn-normal data-sku-open" style="padding:0px 10px; display:inherit;">
                        <i style="color: #FFFFFF;" class="layui-icon layui-icon-link"></i>
                    </button>
                </td>
                <td><input class="layui-input" value="{$info.remark}" type="text" name="info.remark[]"/></td>
                <td>
                    <button type="button" class="layui-btn layui-btn-normal layui-btn-sm data-sku-add" style="margin-bottom: 3px;">
                        <i class="layui-icon layui-icon-add-1"></i>
                    </button>
                    <br/>
                    <button type="button" class="layui-btn layui-btn-danger layui-btn-sm data-sku-remove">
                        <i class="layui-icon layui-icon-delete"></i>
                    </button>
                </td>
                <input type="hidden" name="info.info_id[]" value="{$info.info_id}">
            </tr>
            {/foreach}
            {/if}
            <tr style="background-color: #F2F2F2;">
                <td colspan="2">合计：</td>
                <td class="total-qty">{$purchase?$purchase.total_qty:''}</td>
                <td></td>
                <td class="total-price">{$purchase?$purchase.amo_money|abs:''}</td>
                <td colspan="3"></td>
            </tr>
            </tbody>
        </table>
    </div>
    {if empty($purchase) || (\app\common\model\JobFlowModule::isCheckWait($purchase) && in_array($purchase->getData('order_status'), $order_status_wait))}
    <div class="layui-form-item">
        <div class="layui-col-xs12 text-center">
            <button type="reset" class="layui-btn ">重置</button>
            <button type="submit" class="layui-btn layui-btn-normal" lay-submit lay-filter="purchase-form">保存</button>
        </div>
    </div>
    {/if}
</form>
<script type="text/html" id="data-sku-template">
    <tr class="data-sku-row">
        <td><img class="sku-img" src="__PUBLIC__/img/no-photo.png"/></td>
        <td>
            <div class="more-select-sku"></div>
        </td>
        <td><input class="layui-input qty" value="1" type="number" name="info.qty[]" lay-reqText="数量必填" lay-verify="required"/></td>
        <td><input class="layui-input price" type="number" lay-reqText="单价必填" lay-verify="required" name="info.price[]"/></td>
        <td class="sum-one-price"></td>
        <td>
            <div class="layui-input-inline" style="margin-right: 0px; width: 80%;">
                <input class="layui-input purl" type="text" name="info.url[]" lay-verify="emptyUrl"/>
            </div>
            <button type="button" class="layui-btn layui-btn-normal data-sku-open" style="padding:0px 10px; display:inherit;">
                <i style="color: #FFFFFF;" class="layui-icon layui-icon-link"></i>
            </button>
        </td>
        <td><input class="layui-input" type="text" name="info.remark[]"/></td>
        <td>
            <button type="button" class="layui-btn layui-btn-normal layui-btn-sm data-sku-add" style="margin-bottom: 3px;">
                <i class="layui-icon layui-icon-add-1"></i>
            </button>
            <br/>
            <button type="button" class="layui-btn layui-btn-danger layui-btn-sm data-sku-remove">
                <i class="layui-icon layui-icon-delete"></i>
            </button>
        </td>
    </tr>
</script>
{include file="pur/purchase/check" /}
{/block}
{block name="script"}
<script type="text/javascript" src="__PUBLIC__/js/jquery.serializejson.min.js"></script>
<script type="text/javascript">
    //一般直接写在一个js文件中
    layui.extend({
        xmSelect: 'xm-select',
        inputTags: "inputTags"
    }).use(['layer', 'form', 'jquery', 'laydate', 'longli', 'xmSelect', 'upload', 'inputTags'], function()
    {
        var layer = layui.layer
            , form = layui.form
            , upload = layui.upload
            , $ = layui.jquery;

        // 选择 sku
        $(".more-select-sku").each(function()
        {
            var sku = $(this).attr("item");
            renderSearch(this, sku.trim());
        });

        // 上传发票合同
        $("#upload-contract, #upload-invoice").each(function()
        {
            var $this = $(this);
            upload.render({
                elem: this
                , url: '{:url("file/upload",["type"=>"document"])}'
                , accept: 'file' //普通文件
                , field: "file"
                , multiple: true
                , before: function (obj) {
                    layer.load(0, {shade: false});
                }
                , done: function (response, index, upload) {
                    layer.closeAll('loading');

                    if (response.code != 1) {
                        layer.closeAll('loading');
                        var icon = response.code == 1 ? 6 : 5;
                        layer.msg(response.msg, {icon: icon, time: 1500});
                        return;
                    }
                    var type = $this.attr("item");
                    var purId = {$purchase ? $purchase.purchase_id : 0}
                    , attachment = $this.attr("id").replace("upload", "attachment")
                    , $ment = $("#" + attachment);
                    var fileVal = $ment.val().split(",").filter((e)=>{return e !="";});
                    fileVal.push(response.data.src);
                    $ment.val(layui.longli.uniqueArray(fileVal).join(","));
                    if(purId == 0) return;
                    $.post("{:url('upload')}", {"path": response.data.src, "name": response.data.name, "type": type, "purchase_id": purId}).done(function (response)
                    {
                        var icon = response.code == 1 ? 6 : 5;
                        layer.msg(response.msg, {icon: icon, time: 1500});
                    });
                }
                , error: function (index, upload) {
                    layer.msg('上传失败');
                }
            });
        });

        // 自动添加采购详情
        if($(".layui-table .data-sku-row").length < 1)
        {
            var html = $("#data-sku-template").html();
            $(".layui-table tbody").prepend(html);
            form.render("select");
            renderSearch($(".layui-table .more-select-sku:last").get(0));
        }
        // 添加行
        $(".layui-table").on("click", ".data-sku-add", function()
        {
            var html = $("#data-sku-template").html();
            $(".layui-table .data-sku-row:last").after(html);
            form.render("select");
            renderSearch($(".layui-table .more-select-sku:last").get(0));
        });
        // 删除行
        $(".layui-table").on("click", ".data-sku-remove",function()
        {
            if($(".layui-table .data-sku-row").length == 1)
            {
                layer.msg('只有一条不允许删除。', {time : 2000});
                return;
            }
            $(this).parent().parent().remove();
        });

        // 表格计算
        $(".layui-table").on("change", "input.qty,input.price", function()
        {
            calculateTable();
        });
        function calculateTable()
        {
            var sQty = 0, totalPrice = 0;
            $("input.qty").each(function()
            {
                var $this = $(this)
                    , $tr = $this.parent().parent()
                    , qty = +$this.val(),
                    price = +$tr.find(".price").val();
                if(qty < 1)
                {
                    layer.msg("数量不能小于1");
                    return false;
                }
                if(price <= 0)
                {
                    layer.msg("价格必须大于0");
                    return false;
                }
                var onePrice = (qty * price).toFixed(2) * 1;
                sQty += qty;
                totalPrice += onePrice;
                $tr.find(".sum-one-price").text(onePrice);
            });
            $(".total-qty").text(sQty);
            $(".total-price").text(totalPrice.toFixed(2));
        }

        // 提交表单
        form.on("submit(purchase-form)", function (data)
        {
            // 手动验证价格和数量
            var flag = false;
            $("form input.qty, form input.price").each(function()
            {
                if($(this).val() * 1 <= 0)
                {
                    $(this).focus();
                    flag = true;
                    return false;
                }
            });
            if(flag)
            {
                layer.msg('采购详情有误，请检查', {time : 2000});
                return false;
            }
            var json = $("#purchase-form").serializeJSON();
            layui.longli.postJson('{:url("/pur/purchase/add")}', json, function(response)
            {
                var icon = response.code == 1 ? 6 : 5;
                layer.msg(response.msg, {icon: icon, time: 1500}, function()
                {
                    if(response.code == 1)
                    {
                        location.href = "{:url('pur/purchase/index')}";
                    }
                });
            });
            return false;
        });

        // 表单验证
        form.verify({
            egtZero: function(value)
            {
                if(value.length > 0 && value < 0) return "必须大于等于0";
            }
        });
        // 填充收货人信息
        form.on("select(warehouse)", function(data)
        {
            if(!data.value) return;
            $.get("{:url('wms/warehouse/get')}", {warehouse_id:data.value}).done(function(response)
            {
                if(response.code != 1) return;
                ["address", "phone", "contacts"].forEach(function(value)
                {
                    if(response.data[value].length > 0)
                    {
                        $("#"+value).val(response.data[value]);
                    }
                });
            });
        });

        // 处理选择供应商
        form.on("select(producer)", function(data)
        {
            if(!data.value) return;
            $.get("{:url('pur/producer/get')}", {"producer_id":data.value}).done(function(response)
            {
                if(response.code != 1) return false;
                $("#purchase-pay-type option").each(function()
                {
                    var $this = $(this);
                    if($this.val() == response.data.pay_type)
                    {
                        $this.attr("selected", true);
                        $this.siblings().removeAttr("selected");
                        return false;
                    }
                });
                $("#purchase-invoice option").each(function()
                {
                    var $this = $(this);
                    if($this.val() == response.data.is_invoice)
                    {
                        $this.attr("selected", true);
                        $this.siblings().removeAttr("selected");
                        return false;
                    }
                });
                $("#purchase-credit-day").val(response.data.credit_day);
                $("#estimate-date").val(layui.longli.addDay(response.data.delivery_day));
                form.render("select");
            });
        });

        $(".layui-table").on("click", ".data-sku-open", function()
        {
            var url = $(this).parent().find(".purl").val().trim();
            if(url) window.open(url, "_blank");
        });

        // 下单
        $("#purchase-business").click(function()
        {
            generateOrder($(this).attr("item"), function()
            {
                location.reload();
            });
        });

        // 申请付款
        $("#purchase-payment").click(function()
        {
            generatePayment($(this).attr("item"), function(response)
            {
                if(response.code == 1) location.reload();
            });
        });

        // 取消
        $("#purchase-cancel").click(function()
        {
            cancelPurchase($(this).attr("item"), function(response)
            {
                if(response.code == 1) location.reload();
            });
        });

        /**
         * 渲染多选下拉框
         * @param node 需要渲染的节点
         * @param defVal 默认值
         */
        function renderSearch(node, defVal)
        {
            var xargs = {
                el: node,
                radio: true,
                clickClose: true,
                prop: {
                    name: 'sku',
                    value: 'sku',
                },
                name: 'info.sku[]',
                filterable: true,
                remoteSearch: true,
                on: function(data)
                {
                    if(data.change.length < 1) return;
                    var current = data.change[0];
                    $tr = $(node).parent().parent();
                    $tr.find(".sku-img").attr("src", current.image_url);

                    if(current.price) $tr.find(".price").val(current.price);
                    var url = "", p = [];
                    if(current.product && current.product.purchase) p = current.product.purchase;
                    for(var i in p)
                    {
                        if(url == "") url = p[i].url;
                        if(p[i].is_default == 1)
                        {
                            url = p[i].url;
                            break;
                        }
                    }
                    $tr.find(".purl").val(url);
                    calculateTable();
                },
                remoteMethod: function (text, callback, show)
                {
                    text = text.trim();
                    if (!text) return callback([]);
                    $.get("{:url('wms/product/get')}", {sku: text, more: 1}).done(function (response)
                    {
                        if(response.code != 1) return callback([]);
                        callback(response.data);
                    });
                }
            };
            if(defVal) xargs.data =  [{sku: defVal, selected: true}];
            layui.xmSelect.render(xargs);
        }
    });
</script>
{/block}